<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="缓存1.mysql缓存  相同的查询被执行多次，结果就会放进缓存中，下次再次执行就直接返回缓存的数据  但是:如果sql中包含now(),RAND()等函数则不会开启缓存  insert,delete,update这些操作会使缓存失效  sql1.使用explain分析sql  explain select * from a left join b on a.uid = b.uid where a">
<meta property="og:type" content="article">
<meta property="og:title" content="mysql性能优化">
<meta property="og:url" content="http://yoursite.com/2017/08/30/mysql/mysql性能优化/index.html">
<meta property="og:site_name" content="Tissan">
<meta property="og:description" content="缓存1.mysql缓存  相同的查询被执行多次，结果就会放进缓存中，下次再次执行就直接返回缓存的数据  但是:如果sql中包含now(),RAND()等函数则不会开启缓存  insert,delete,update这些操作会使缓存失效  sql1.使用explain分析sql  explain select * from a left join b on a.uid = b.uid where a">
<meta property="og:image" content="http://yoursite.com/uploads/mysql/mysql-enum.jpg">
<meta property="og:image" content="http://yoursite.com/uploads/mysql/mysql1.png">
<meta property="og:updated_time" content="2017-10-30T13:11:01.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="mysql性能优化">
<meta name="twitter:description" content="缓存1.mysql缓存  相同的查询被执行多次，结果就会放进缓存中，下次再次执行就直接返回缓存的数据  但是:如果sql中包含now(),RAND()等函数则不会开启缓存  insert,delete,update这些操作会使缓存失效  sql1.使用explain分析sql  explain select * from a left join b on a.uid = b.uid where a">
<meta name="twitter:image" content="http://yoursite.com/uploads/mysql/mysql-enum.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 'undefined',
      author: 'Java程序员'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/08/30/mysql/mysql性能优化/"/>





  <title>mysql性能优化 | Tissan</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tissan</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/08/30/mysql/mysql性能优化/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="罗天翔">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tissan">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">mysql性能优化</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-30T16:12:09+08:00">
                2017-08-30
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/mysql/" itemprop="url" rel="index">
                    <span itemprop="name">mysql</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/2017/08/30/mysql/mysql性能优化/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2017/08/30/mysql/mysql性能优化/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <h4 id="缓存"><a href="#缓存" class="headerlink" title="缓存"></a>缓存</h4><p>1.mysql缓存<br>  相同的查询被执行多次，结果就会放进缓存中，下次再次执行就直接返回缓存的数据<br>  但是:如果sql中包含now(),RAND()等函数则不会开启缓存</p>
<blockquote>
<p>insert,delete,update这些操作会使缓存失效</p>
</blockquote>
<h4 id="sql"><a href="#sql" class="headerlink" title="sql"></a>sql</h4><p>1.使用explain分析sql<br>  explain select * from a left join b on a.uid = b.uid where a.uid = 22<br>  -&gt; 查询行数是全表查询<br>  加上uid索引<br>  -&gt; 查询的行为uid所在的行号</p>
<p>2.只要一条数据 limit1</p>
<p>3.避免select *</p>
<p>4.is not null(建议使用)<br>  尽量sql中使用 is not null,因为null不是真正的为空它还是会和查询字段进行比较的</p>
<p>5.delete，insert拆分，因为这两个操作会锁表，当锁上30s后，那些等待的线程<br>数据库链接，打开的文件可能会crash掉服务器所以尽量将delete，insert拆分成多次</p>
<h4 id="建表"><a href="#建表" class="headerlink" title="建表"></a>建表</h4><p>1.使用ENUM类型,实际上存的是tinyint但是展示的是varchar<br><img src="/uploads/mysql/mysql-enum.jpg" alt="流程图"></p>
<p>2.存ip地址可以存储UNSIGNED INT，将ip转化成为一个整形这样查询ip可以使用ip between ip1 and ip2</p>
<p>3.使用固定长度会更快 固定长度更容易计算下一个数据的偏移量，每次查询需要到程序中查找主键</p>
<p>4.将数据表切分拆分比如用户表的收货地址不要和用户表放在一起，因为用户的账号，角色会被经常用到</p>
<h4 id="索引"><a href="#索引" class="headerlink" title="索引"></a>索引</h4><p>1.join的时候关联的字段应该都要被加上索引，并且需要相同的字符集<br>  select * from a left join b on a.uid = b.uid where a.uid = 22<br>  a的uid和b的uid应该都要在各自表中加上索引</p>
<h4 id="orm框架-插件"><a href="#orm框架-插件" class="headerlink" title="orm框架/插件"></a>orm框架/插件</h4><p>1.Prepared Statements是一种运行在后台的sql语句集合<br>好处:防sql注入，现在很多orm框架支持(mybatis)</p>
<p>2.选择innodb索引，行锁 MVCC 写操作比较多时，性能优于myisam</p>
<h4 id="痛点"><a href="#痛点" class="headerlink" title="痛点:"></a>痛点:</h4><p>1.全表查询:<br>(1)like ‘%..%’全模糊，放弃索引，全表查询, 改成 like ‘..%’<br>(2)is null单索引失效<br>(3)&lt;&gt; 不等于会引起全表查询，改成 a &lt; 2 or a &gt; 2</p>
<h4 id="sql调优"><a href="#sql调优" class="headerlink" title="sql调优"></a>sql调优</h4><p>1.explain:<br><img src="/uploads/mysql/mysql1.png" alt="mysql-explain"><br>(1)type:</p>
<ul>
<li>const：表最多有一个匹配行，一般是根据主键查，或者唯一索引，达到常量级别，性能很好</li>
<li>ref：  通过索引，可以直接引用到某些数据行</li>
<li>range：根据索引做范围扫描</li>
<li>index：扫描所有的索引节点</li>
<li>all：全表扫描<br>(2)possible key:可能用到的索引<br>(3)key:最终使用的索引</li>
</ul>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/uploads/wechat.png" alt="罗天翔 WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/uploads/ali.jpg" alt="罗天翔 Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/26/jvm/深入理解JVM-优化/" rel="next" title="编译器优化">
                <i class="fa fa-chevron-left"></i> 编译器优化
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/09/01/mysql/事务/" rel="prev" title="mysql innodb事务">
                mysql innodb事务 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.jpg"
               alt="罗天翔" />
          <p class="site-author-name" itemprop="name">罗天翔</p>
           
              <p class="site-description motion-element" itemprop="description">一次就把事情做对.</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">74</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">15</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/louiegit/" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="" target="_blank" title="微信">
                  
                    <i class="fa fa-fw fa-wechat"></i>
                  
                  微信
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#缓存"><span class="nav-number">1.</span> <span class="nav-text">缓存</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#sql"><span class="nav-number">2.</span> <span class="nav-text">sql</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#建表"><span class="nav-number">3.</span> <span class="nav-text">建表</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#索引"><span class="nav-number">4.</span> <span class="nav-text">索引</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#orm框架-插件"><span class="nav-number">5.</span> <span class="nav-text">orm框架/插件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#痛点"><span class="nav-number">6.</span> <span class="nav-text">痛点:</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#sql调优"><span class="nav-number">7.</span> <span class="nav-text">sql调优</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">罗天翔</span>
</div>


<div class="powered-by">
  NBA & Code. What?
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cyt9ceIwz';
      var conf = 'c6226e2bfb7e9c65efc235736edc5074';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  




  





  

  

  

  

  

  

</body>
</html>
